<template>
    <div>
        <!--        -->
        <el-dialog
                title="修改用户信息"
                v-model="dialogFormVisible">
            <el-form v-model="selectedUser" style="text-align: left" ref="dataForm">
                <el-form-item label="用户名" label-width="120px" prop="username">
                    <label>{{ selectedUser.username }}</label>
                </el-form-item>
                <el-form-item label="真实姓名" label-width="120px" prop="name">
                    <el-input v-model="selectedUser.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机号" label-width="120px" prop="phone">
                    <el-input v-model="selectedUser.phone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" label-width="120px" prop="email">
                    <el-input v-model="selectedUser.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" label-width="120px" prop="password">
                    <el-button type="warning" @click="resetPassword(selectedUser.username)">重置密码</el-button>
                </el-form-item>
                <el-form-item label="角色分配" label-width="120px" prop="roles">
                    <el-checkbox-group v-model="selectedRolesIds">
                        <el-checkbox v-for="(role,i) in roles" :key="i" :label="role.id">{{ role.nameZh }}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <!--      slot="footer"      -->
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="onSubmit(selectedUser)">确 定</el-button>
            </div>
        </el-dialog>
        <el-row style="margin: 18px 0px 0px 18px ">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/admin/dashboard' }">管理中心</el-breadcrumb-item>
                <el-breadcrumb-item>用户管理</el-breadcrumb-item>
                <el-breadcrumb-item>用户信息</el-breadcrumb-item>
            </el-breadcrumb>
        </el-row>
        <bulk-registration @onSubmit="listUsers()"></bulk-registration>
        <el-card style="margin: 18px 2%;width: 95%">
            <el-table
                    ref="multipleTable"
                    :data="users"
                    stripe
                    :default-sort="{prop: 'id', order: 'ascending'}"
                    style="width: 100%"
                    :max-height="tableHeight"
                    @selection-change="opt">
                <el-table-column
                        type="selection"
                        width="55">
                </el-table-column>
                <el-table-column
                        prop="id"
                        label="id"
                        sortable
                        width="100">
                </el-table-column>
                <el-table-column
                        prop="username"
                        label="用户名"
                        fit>
                </el-table-column>
                <el-table-column
                        prop="name"
                        label="真实姓名"
                        fit>
                </el-table-column>
                <el-table-column
                        prop="phone"
                        label="手机号"
                        fit>
                </el-table-column>
                <el-table-column
                        prop="email"
                        label="邮箱"
                        show-overflow-tooltip
                        fit>
                </el-table-column>
                <el-table-column
                        label="状态"
                        sortable
                        width="100">
                    <template v-slot="scope">
                        <el-switch
                                v-model="scope.row.enabled"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                @change="(value) => commitStatusChange(value, scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                        label="操作"
                        width="120">
                    <template v-slot="scope" >
<!--            size="small"            -->
                        <el-button
                                @click="editUser(scope.row)"
                                type="text">
                            编辑
                        </el-button>
<!--                size="small"       -->
                        <el-button
                                @click = "deleteUser(scope.row)"
                                type="text">
                            移除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="margin: 20px 0 20px 0;float: left">
                <el-button @click="deselect">取消选择</el-button>
                <el-button @click="deleteUsers()">批量删除</el-button>
            </div>
        </el-card>
    </div>
</template>

<script>
    import BulkRegistration from './BulkRegistration'
    import {computed, getCurrentInstance, onMounted, reactive, toRefs} from "vue";

    export default {
        name: 'UserProfile',
        components: {BulkRegistration},
        setup() {
            const data = reactive({
                users: [],
                roles: [],
                dialogFormVisible: false,
                selectedUser: [],
                selectedRolesIds: [],
                optionUsers :[]
            })
            onMounted(() => {
                listUsers()
                // listRoles()
            })

            let tableHeight = computed(() => {
                return window.innerHeight - 320
            })

            let {proxy} = getCurrentInstance()

            function listUsers() {
                proxy.$axios.get('/admin/user').then(resp => {
                    if (resp && resp.data.code === 200) {
                        data.users = resp.data.result
                    }
                }).catch(failResponse => {
                    console.log(failResponse)
                })
            }

            function listRoles() {
                proxy.$axios.get('/admin/role').then(resp => {
                    if (resp && resp.data.code === 200) {
                        data.roles = resp.data.result
                    }
                }).catch(failResponse => {
                    console.log(failResponse)
                })
            }

            function commitStatusChange(value, user) {
                if (user.username !== 'admin') {
                    proxy.$axios.put('/admin/user/status', {
                        enabled: value,
                        username: user.username
                    }).then(resp => {
                        if (resp && resp.data.code === 200) {
                            if (value) {
                                proxy.$message('用户 [' + user.username + '] 已启用')
                            } else {
                                proxy.$message('用户 [' + user.username + '] 已禁用')
                            }
                        }
                    }).catch(failResponse => {
                        console.log(failResponse)
                    })
                } else {
                    user.enabled = true
                    proxy.$alert('不能禁用管理员账户')
                }
            }

            function onSubmit(user) {
                // console.log(user)
                // 根据视图绑定的角色 id 向后端传送角色信息
                let roles = []
                for (let i = 0; i < data.selectedRolesIds.length; i++) {
                    for (let j = 0; j < data.roles.length; j++) {
                        if (data.selectedRolesIds[i] === data.roles[j].id) {
                            roles.push(data.roles[j])
                        }
                    }
                }
                proxy.$axios.put('/admin/user', {
                    id:user.id,
                    username: user.username,
                    name: user.name,
                    phone: user.phone,
                    email: user.email,
                  //  roles: roles
                }).then(resp => {
                    if (resp && resp.data.code === 200) {
                        proxy.$alert('用户信息修改成功')
                        data.dialogFormVisible = false
                        // 修改角色后重新请求用户信息，实现视图更新
                        listUsers()
                    } else {
                        proxy.$alert(resp.data.message)
                    }
                }).catch(failResponse => {
                    console.log(failResponse)
                })
            }

            function editUser(user) {
                data.dialogFormVisible = true
                data.selectedUser = user
                let roleIds = []
                for (let i = 0; i < user.roles.length; i++) {
                    roleIds.push(user.roles[i].id)
                }
                data.selectedRolesIds = roleIds
            }

            function resetPassword(username) {
                proxy.$axios.put('/admin/user/password', {
                    username: username
                }).then(resp => {
                    if (resp && resp.data.code === 200) {
                        proxy.$alert('密码已重置为 123')
                    }
                }).catch(failResponse => {
                    console.log(failResponse)
                })
            }

            function deleteUser(user){
                let allow = false
                data.optionUsers.forEach(opt => {
                    if(user.id === opt.id){
                        allow = true
                    }
                })
                if (allow === true){
                    proxy.$axios.post('/user/delete',{
                        id : user.id
                    }).then(resp =>{
                        console.log(resp)
                        listUsers()
                    }).catch(failResponse => {
                        console.log(failResponse)
                    })
                }else {
                    proxy.$alert('未选中无法进行删除')
                }


            }

            function deleteUsers(){
                proxy.$confirm('删除后无法恢复，请确定','提示').then(()=>{
                    data.optionUsers.forEach(user => {
                        deleteUser(user)
                    })
                }).catch(()=>{
                    console.log('取消删除')
                })

            }

            function opt(user){
                data.optionUsers = user
            }

            function deselect(){
                proxy.$refs.multipleTable.clearSelection()
            }


            return {
                ...toRefs(data),
                onMounted,
                listUsers,
                onSubmit,
                resetPassword,
                editUser,
                commitStatusChange,
                tableHeight,
                listRoles,
                deleteUser,
                deleteUsers,
                deselect,
                opt
            }
        }

    }
</script>

<style scoped>

</style>
